package com.sjd.mall.service.goods.impl;

import com.sjd.mall.domain.SjdGoodsDiscountDO;
import com.sjd.mall.mapper.SjdGoodsDiscountMapper;
import com.sjd.mall.service.goods.GoodsDiscountService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author : Mr.s
 * @version : 1.0
 * @description : 商品折扣serviceimpl
 * @date : 2022-01-13 10:44
 */
@Service
public class GoodsDiscountServiceImpl implements GoodsDiscountService {

    @Autowired
    private SjdGoodsDiscountMapper goodsDiscountMapper;
    @Autowired
    private RedisTemplate<String, String> stringRedisTemplate;

    private static final String SJD_GOODS_MEMBER_LEVEL_DISCOUNT = "sjd:goods:memberLevelDiscount:";


    /**
     * 初始化商品折扣
     *
     * @return return
     */
    @Override
    public boolean initGoodsDiscount() {
        List<SjdGoodsDiscountDO> allGoodsDiscount = goodsDiscountMapper.getEnableGoodsDiscount();
        for (SjdGoodsDiscountDO discountDO : allGoodsDiscount) {
            stringRedisTemplate.opsForValue().set(SJD_GOODS_MEMBER_LEVEL_DISCOUNT + discountDO.getMemberLevel(), discountDO.getGoodsDiscount().toString());
        }
        return true;
    }

    /**
     * 设置/修改 商品折扣
     *
     * @param memberLevel memberLevel
     * @param discount    discount
     * @return return
     */
    @Override
    public boolean setGoodsDiscount(Integer memberLevel, BigDecimal discount) {
        SjdGoodsDiscountDO sjdGoodsDiscountDO = new SjdGoodsDiscountDO();
        sjdGoodsDiscountDO.setMemberLevel(memberLevel);
        sjdGoodsDiscountDO.setGoodsDiscount(discount);
        goodsDiscountMapper.insert(sjdGoodsDiscountDO);
        stringRedisTemplate.opsForValue().set(SJD_GOODS_MEMBER_LEVEL_DISCOUNT + memberLevel, discount.toString());
        return false;
    }

    /**
     * 获取商品折扣
     *
     * @param memberLevel memberLevel
     * @return return
     */
    @Override
    public BigDecimal getGoodsDiscount(Integer memberLevel) {
        String discountStr = stringRedisTemplate.opsForValue().get(SJD_GOODS_MEMBER_LEVEL_DISCOUNT + memberLevel);
        if (StringUtils.isEmpty(discountStr)) {
            return null;
        }
        return new BigDecimal(discountStr);
    }

    /**
     * 删除商品折扣
     *
     * @param memberLevel memberLevel
     * @return return
     */
    @Override
    public boolean delGoodsDiscount(Integer memberLevel) {
        stringRedisTemplate.delete(SJD_GOODS_MEMBER_LEVEL_DISCOUNT + memberLevel);
        return false;
    }

}
